import { AudioFrequencyInfo } from "../../../mode/audioFrequency";

Component({
  options: {
    addGlobalClass: true,
    pureDataPattern: /^_/
  },
  properties: {
    duration: {
      type: Number,
      value: 500
    },
    type: {
      type: String,
      value: 'video'
    },
    easingFunction: {
      type: String,
      value: 'default'
    },
    loop: {
      type: Boolean,
      value: true
    },
    videoList: {
      type: Array,
      value: [],
      observer: function observer() {
        var newVal = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

        this._videoListChanged(newVal);
      }
    }
  },
  data: {
    nextQueue: <any>[],
    prevQueue: <any>[],
    curQueue: <any>[],
    circular: false,
    _last: 1,
    _change: -1,
    _invalidUp: 0,
    _invalidDown: 0,
    _videoContexts: <any[]>[],
    paused: <boolean>false,
    audioCtx: <WechatMiniprogram.BackgroundAudioManager>{},
    currentValue: 10,
    startX: 0,
    towards: '',
    current: 0,

    isProgress: true, // 播放进度条是否显示
    progress: 0, // 当前音频的播放位置
    buffered: 0, // 音频已缓冲的时间
    previewProgress: 0,
    currentAudioInfo: <AudioFrequencyInfo>{},

    classCollection: false,
    options: [
      [
        { name: '微信', icon: 'wechat' },
        { name: '微博', icon: 'weibo' },
        { name: 'QQ', icon: 'qq' },
        {
          name: '火花',
          icon: 'https://img.yzcdn.cn/vant/custom-icon-fire.png',
        }
      ],
      [
        { name: '复制链接', icon: 'link', description: '描述信息', },
        { name: '分享海报', icon: 'poster' },
        { name: '二维码', icon: 'qrcode' },
        {
          name: '水滴',
          icon: 'https://img.yzcdn.cn/vant/custom-icon-light.png',
        },
      ],
    ],
  },
  lifetimes: {
    attached: function attached() {
      console.log('初始化', this.properties.videoList);
      const audioCtx = wx.getBackgroundAudioManager();
      this.setData({
        audioCtx
      });

      // const audioFrequency = this.properties.videoList[0];
      // audioCtx.title = audioFrequency.name;
      // audioCtx.src = audioFrequency.audio_url;
      // audioCtx.seek(223.000);
      // audioCtx.pause();

      this.data._videoContexts = [wx.createVideoContext('video_0', this), wx.createVideoContext('video_1', this), wx.createVideoContext('video_2', this)];
    }

  },
  observers: {
    'audioCtx': function () {
      const {
        audioCtx,
        videoList,
        current
      } = this.data;
      const that = this;
      console.log('变化', audioCtx, videoList, current);




      /** 音频对应操作 */
      audioCtx.onCanplay(function () {
        console.log('当前音频的长度:', audioCtx.duration);
        
      });
      audioCtx.onPlay(function () {
        console.log('当前音频的长度:', wx.getBackgroundAudioManager().duration);
        console.log('当前音频的状态:', wx.getBackgroundAudioManager().paused);
        console.log('当前音频的地址:', wx.getBackgroundAudioManager().src);
        const currentAudioInfo = videoList.filter(val => val.audio_url === audioCtx.src)[0]; 
        console.log(videoList, currentAudioInfo);
        
        that.setData({
          pause: wx.getBackgroundAudioManager().paused,
          currentAudioInfo, /** 当前歌曲信息 */
        });
        
    
      });
      audioCtx.onWaiting(function (res) {
        console.log('音频加载中', res);
      });
      audioCtx.onError(function (res) {
        console.log('音频加载出错', res);
      });
      audioCtx.onTimeUpdate(function () {
        // console.log('当前音频的长度:', audioCtx.duration);
        // console.log('当前音频的播放位置:', audioCtx.currentTime);
        // console.log('音频已缓冲的时间:', audioCtx.buffered);
        const progress = audioCtx.currentTime / audioCtx.duration;
        const buffered = audioCtx.buffered / audioCtx.duration;
        that.setData({
          progress: progress * 100,
          buffered: buffered * 100
        })

      });
      audioCtx.onNext(function (res) {
        console.log('下一曲', res);
      });
      audioCtx.onPrev(function (res) {
        console.log('上一曲', res);
      });
      audioCtx.onEnded(function () {
        console.log('播放结束', current);
        const currentAdd = current + 1;
        that.setData({
          current: currentAdd,
        });
        const audioFrequency = videoList[currentAdd];
        console.log(audioFrequency)
        audioCtx.title = audioFrequency.name;
        audioCtx.src = audioFrequency.audio_url;
      });
    }
  },

  methods: {

    /** 收藏 */
    onCollection() {
      this.setData({ classCollection: !this.data.classCollection });
    },
    /** 打开评论 */
    onShowComment() {
      this.getTabBar().hidden();
      this.setData({ showComment: true });
    },

    /** 打开分享 */
    onShowShare() {
      this.getTabBar().hidden();
      this.setData({ showShare: true });
    },
    /** 关闭评论 / 分享 */
    onClose() {
      this.getTabBar().hidden();
      this.setData({ showShare: false, showComment: false });
    },

    onSelect(event: any) {
      wx.showToast({ title: event.detail.name, icon: 'none' });
      this.onClose();
    },

    audioControl: function () {
      const {
        audioCtx
      } = this.data;
      console.log(audioCtx, audioCtx.paused);
      this.setData({
        pause: !this.data.paused
      });
      if (audioCtx.paused) {
        console.log('播放', audioCtx);
        audioCtx.play();
      } else {
        console.log('暂停', audioCtx);
        audioCtx.pause();

      }
    },

    onChange(event: any) {
      wx.showToast({
        icon: 'none',
        title: `当前值：${event.detail}`,
      });
    },

    touchStart: function (e: any) {

      if (e.touches.length == 1) {
        this.setData({
          isProgress: false,
          startX: e.touches[0].clientX,
          previewProgress: this.data.progress,
        });
      }
    },
    touchMove: function (e: any) {
      const {
        previewProgress
      } = this.data;
      const windowWidth = wx.getSystemInfoSync().windowWidth;
      if (e.touches.length == 1) {
        var moveX = e.touches[0].clientX;
        var towards = this.data.startX - moveX;

        if (towards > windowWidth) {
          towards = windowWidth;
        }
        const amountChange = towards / windowWidth / 40 * 100;
        let offset = 0;
        previewProgress > amountChange ? offset = previewProgress - amountChange : offset = 0;
        this.setData({
          towards: String(towards),
          previewProgress: offset
        })
      }
    },
    touchEnd: function () {
      const {
        audioCtx,
        previewProgress
      } = this.data;

      const seek = previewProgress / 100 * audioCtx.duration;
      audioCtx.seek(seek);
      // if (that.data.towards != '') {
      //     if (that.data.towards < -20) { //向右
      //         console.log('向右');
      //         wx.showToast({
      //             icon: 'none',
      //             title: '向右',
      //         });
      //     } else if (that.data.towards > 20) { //向左
      //         console.log('向左');
      //         wx.showToast({
      //             icon: 'none',
      //             title: '向左',
      //         });
      //     }
      // }
      this.setData({
        towards: '',
        isProgress: true,
      })
    },






    _videoListChanged: function _videoListChanged(newVal: any[]) {
      var _this = this;
      var data = this.data;
      newVal.forEach(function (item) {
        data.nextQueue.push(item);
      });
      if (data.curQueue.length === 0) {
        this.setData({
          curQueue: data.nextQueue.splice(0, 3)
        }, function () {
          _this.playCurrent(1);
        });
      }
    },
    animationfinish: function animationfinish(e: any) {



      var _data = this.data,
        _last = _data._last,
        _change = _data._change,
        curQueue = _data.curQueue,
        prevQueue = _data.prevQueue,
        nextQueue = _data.nextQueue,
        videoList = _data.videoList;

      var current = e.detail.current;
      var diff = current - _last;
      if (diff === 0) return;
      this.data._last = current;
      this.playCurrent(current);
      this.triggerEvent('change', {
        activeId: curQueue[current].id
      });
      var direction = diff === 1 || diff === -2 ? 'up' : 'down';
      if (direction === 'up') {
        console.log('up');

        const audioFrequency = videoList[current--];
        console.log(audioFrequency)
        wx.getBackgroundAudioManager().src = audioFrequency.audio_url;
        wx.getBackgroundAudioManager().title = audioFrequency.name;
        if (this.data._invalidDown === 0) {
          var change = (_change + 1) % 3;
          var add = nextQueue.shift();
          var remove = curQueue[change];
          if (add) {
            prevQueue.push(remove);
            curQueue[change] = add;
            this.data._change = change;
          } else {
            this.data._invalidUp += 1;
          }
        } else {
          this.data._invalidDown -= 1;
        }
      }
      if (direction === 'down') {
        console.log('down');

        const audioFrequency = videoList[current++];
        console.log(audioFrequency)
        wx.getBackgroundAudioManager().src = audioFrequency.audio_url;
        wx.getBackgroundAudioManager().title = audioFrequency.name;


        if (this.data._invalidUp === 0) {
          var _change2 = _change;
          var _remove = curQueue[_change2];
          var _add = prevQueue.pop();
          if (_add) {
            curQueue[_change2] = _add;
            nextQueue.unshift(_remove);
            this.data._change = (_change2 - 1 + 3) % 3;
          } else {
            this.data._invalidDown += 1;
          }
        } else {
          this.data._invalidUp -= 1;
        }
      }
      var circular = true;
      if (nextQueue.length === 0 && current !== 0) {
        circular = false;
      }
      if (prevQueue.length === 0 && current !== 2) {
        circular = false;
      }
      this.setData({
        curQueue: curQueue,
        circular: circular
      });
    },
    playCurrent: function playCurrent(current: number) {
      this.data._videoContexts.forEach(function (ctx, index) {
        index !== current ? ctx.pause() : ctx.play();
      });
    },
    onPlay: function onPlay(e: any) {
      this.trigger(e, 'play');
    },
    onPause: function onPause(e: any) {
      this.trigger(e, 'pause');
    },
    onEnded: function onEnded(e: any) {
      this.trigger(e, 'ended');
    },
    onError: function onError(e: any) {
      this.trigger(e, 'error');
    },
    onTimeUpdate: function onTimeUpdate(e: any) {
      this.trigger(e, 'timeupdate');
      console.log(e, '1');

    },
    onWaiting: function onWaiting(e: any) {
      this.trigger(e, 'wait');
    },
    onProgress: function onProgress(e: any) {
      this.trigger(e, 'progress');
    },
    onLoadedMetaData: function onLoadedMetaData(e: any) {
      this.trigger(e, 'loadedmetadata');
    },
    trigger: function trigger(e: { detail: any; target: { dataset: { id: any; }; }; }, type: string) {
      var ext = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

      var detail = e.detail;
      var activeId = e.target.dataset.id;
      this.triggerEvent(type, Object.assign(Object.assign(Object.assign({}, detail), {
        activeId: activeId
      }), ext));
    }
  }
});